package liangtWorkSpace.simple;

/**
 * @ClassName StrStr
 * @Description : 给定一个 haystack 字符串和一个 needle 字符串，在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在，则返回  -1
 * <p>
 * 来源：力扣（LeetCode）
 * 链接：https://leetcode-cn.com/problems/implement-strstr
 * 著作权归领扣网络所有。商业转载请联系官方授权，非商业转载请注明出处。
 * @Author : LiangT
 * @Date : 2020/6/17 13:39
 */
public class StrStr {
    public int strStr(String haystack, String needle) {
        if (needle == null) {
            return 0;
        }
        if (haystack == null) {
            return -1;
        }
        return haystack.indexOf(needle) - 1;
    }
    public int strStr3(String haystack, String needle) {
        if (needle == null || needle.length() < 1 || needle.equals("") || haystack.hashCode() == needle.hashCode()) {
            return 0;
        }

        if (haystack == null || haystack.length() < needle.length()) {
            return -1;
        }

        for (int i = 0; i < haystack.length(); i++){
            if (i+needle.length() > haystack.length()){
                return -1;
            }
            if (needle.hashCode() == haystack.substring(i, i + needle.length()).hashCode()) {
                return i;
            }
        }
        return  - 1;
    }

    public int strStr2(String haystack, String needle) {
        if (needle == null) {
            return 0;
        }
        if (haystack == null) {
            return -1;
        }
        if (haystack.hashCode() == needle.hashCode()){
            return 0;
        }
        for (int i = 0; i < haystack.length(); i++){
            if (i+needle.length() > haystack.length()){
                return -1;
            }
            if (needle.hashCode() == haystack.substring(i, i + needle.length()).hashCode()) {
                return i;
            }
        }
        return  - 1;
    }


    /**
     * 暴力排序
     * @param haystack
     * @param needle
     * @return
     */
    public static int strStr1(String haystack, String needle) {
        if (needle == null || needle == "" || needle.length() < 1) {
            return 0;
        }
        if (haystack == null) {
            return 0;
        }
        char[] haystackc = haystack.toCharArray();
        char[] haystackn = needle.toCharArray();
        if (haystackc.length == haystackn.length && haystackn.length == 0) {
            return 0;
        }
        if (haystackc.length < haystackn.length) {
            return -1;
        }
        for (int i = 0; i < haystackc.length; i++) {
            for (int j = 0; j < haystackn.length; j++) {
                if (i+j>=haystackc.length){
                    return -1;
                }
                if (haystackc[i + j] != haystackn[j]) {
                    break;
                }
                if (j + 1 == haystackn.length) {
                    return i;
                }
            }
        }
        return -1;
    }

    public static void main(String[] args) {

        System.out.println(strStr1("hello","ll"));
    }
}
